﻿using System;
using System.Web;
using DotNetOpenAuth;

namespace Appetite.Presentation.Web
{
    public class EmbeddedResourceUrlService : IEmbeddedResourceRetrieval
    {
        public Uri GetWebResourceUrl(Type someTypeInResourceAssembly, string manifestResourceName)
        {
            if (manifestResourceName.Contains("http"))
            {
                return new Uri(manifestResourceName);
            }
            
            var assembly = someTypeInResourceAssembly.Assembly;

            string completeUrl = HttpContext.Current.Request.Url.ToString();
            string host = completeUrl.Substring(0, completeUrl.IndexOf(HttpContext.Current.Request.Url.AbsolutePath));

            string applicationPath = HttpContext.Current.Request.ApplicationPath.Substring(1);
            string assemblyFullName = HttpUtility.UrlEncode(assembly.FullName);
            string typeName = HttpUtility.UrlEncode(someTypeInResourceAssembly.ToString());
            string resourceName = HttpUtility.UrlEncode(manifestResourceName);

            var path = string.Format("{0}/{1}/Resource/GetWebResourceUrl?assemblyName={2}&typeName={3}&resourceName={4}",
                                     host,
                                     applicationPath,
                                     assemblyFullName,
                                     typeName,
                                     resourceName);

            return new Uri(path);
        }
    }
}